﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using nicotool;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;

namespace myNico
{
  
  public  class DownloadItemViewModel:INotifyPropertyChanged
  {
      /// <summary>
      /// 获取动画网址信息
      /// </summary>
      /// <param name="sm"></param>
      /// <returns></returns>
      private delegate FlvInfo dl_getInfo(string sm);

      #region 字段
      /// <summary>
      /// 用户多线程同步的对象
      /// </summary>
      static object syncObject = new object();
      /// <summary>
      /// 用于计算速度的临时变量
      /// </summary>
      private long downloadedBytes = 0;
      CustomWebClient client;
      /// <summary>
      /// 动画网址信息
      /// </summary>
      FlvInfo sminfo;
      /// <summary>
      /// 每次读取的字节数
      /// </summary>
      int readBytes = 100 * 1024;

      private long higt_Size = 0;
      /// <summary>
      /// 动画信息
      /// </summary>
      ThumbInfo thumbInfo;
      /// <summary>
      /// 
      /// </summary>
      string path;
      #endregion 

      #region 属性

      private int _xiazflag;
      /// <summary>
      /// 下载状态0为暂停 1为下载 2完成 3发生错误
      /// </summary>
      public int xiazflag { get { return _xiazflag; } set { _xiazflag = value; NotifyPropertyChanged("xiazflag"); } }

      private string _title;
      /// <summary>
      /// 标题
      /// </summary>
      public string title {
          get{
          return _title;
            }
          set
          {
           _title=value   ;
           NotifyPropertyChanged("title");
          }
      }

      private string _smDownlUrl;
      /// <summary>
      /// sm下载路径
      /// </summary>
      public string smDownlUrl { get { return _smDownlUrl; } set { _smDownlUrl = value; NotifyPropertyChanged("smDownlUrl"); } }

      private string _ThumbnailUrl;
      /// <summary>
      /// 预览图路径
      /// </summary>
      public string ThumbnailUrl { get { return _ThumbnailUrl; } set { _ThumbnailUrl = value; NotifyPropertyChanged("ThumbnailUrl"); } }

      private string _Description;
      /// <summary>
      /// 动画信息
      /// </summary>
      public string Description { get { return _Description; }
          set
          {
              _Description = value;
              NotifyPropertyChanged("Description");
          }
      }
      private string _smType;
      /// <summary>
      /// 动画状态
      /// </summary>
      public string smType { get { return _smType; }
          set {
              _smType = value;
              NotifyPropertyChanged("smType");
          }
      }


      private string _movieType;
      /// <summary>
      /// 视频格式
      /// </summary>
      public string movieType
      {
          get { return _movieType; }
          set
          {
              _movieType = value;
              NotifyPropertyChanged("movieType");
          }
      }

      private string _smName;
      /// <summary>
      /// sm号
      /// </summary>
        public string smName { get { return _smName; }
            set { _smName = value;
            NotifyPropertyChanged("smName");
            }
        }

        private bool _isDownloading;
        /// <summary>
        /// 是否正在下载
        /// </summary>
        public bool IsDownloading
        {
            get { return _isDownloading; }
            set
            {
                _isDownloading = value;
                NotifyPropertyChanged("IsDownloading");
            }
        }
        private long _downloadBytes;
        /// <summary>
        /// 已下载的字节数
        /// </summary>
        public long DownloadBytes
        {
            get { return _downloadBytes; }
            set
            {
                _downloadBytes = value;
                NotifyPropertyChanged("DownloadBytes");
            }
        }
        private long _totalBytes;
        /// <summary>
        /// 要下载的字节总数(文件大小)
        /// </summary>
        public long TotalBytes
        {
            get { return _totalBytes; }
            set
            {
                _totalBytes = value;
                NotifyPropertyChanged("TotalBytes");
            }
        }

        private string _fileName;
      /// <summary>
        /// 保存文件名
      /// </summary>
        public string FileName
        {
            get{return _fileName;}
            set
            {

                _fileName = value;
                NotifyPropertyChanged("FileName");
            }
        }
      #endregion

        private double _Progress;
        /// <summary>
        /// 当前进度
        /// </summary>
        public double Progress
        {
            get { return _Progress; }
            set
            {
                _Progress = value;
                NotifyPropertyChanged("Progress");
            }

        }
        //public double Progress
        //{
        //    get { return DownloadBytes * 100.0 / TotalBytes; }
        //}

        private double _speed;
        /// <summary>
        /// 即时速度
        /// </summary>
        public double Speed
        {
            get { return _speed; }
            set
            {
                _speed = value;
                NotifyPropertyChanged("Speed");
            }
        }

        private bool _isCompleted;
        /// <summary>
        /// 是否已完成
        /// </summary>
        public bool IsCompleted
        {
            get { return _isCompleted; }
            set
            {
                _isCompleted = value;
                NotifyPropertyChanged("IsCompleted");
            }
        }

        private string _xiazSize;

        public string xiazSize
        {
        get {return _xiazSize;}
            set
            {
                _xiazSize = value;
                NotifyPropertyChanged("xiazSize");
            }
        }

        public DownloadItemViewModel()
        {

        }

        /// <summary>
      /// 
      /// </summary>
      /// <param name="sm">动画sm号</param>
        public  DownloadItemViewModel(string sm)
        {
            smName = sm;
            //获取cookie
           // client = nicovideo.GetWebClientForFlv(sm);
          //  client.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
      //      client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
                //获取网址信息
             //   sminfo = FlvInfo.Create(sm);
            dl_getInfo dl = new dl_getInfo(getflvinfo);
            IAsyncResult ar = dl.BeginInvoke(sm, null, dl);
            sminfo = dl.EndInvoke(ar);
            smDownlUrl = sminfo.FlvUrl;


                thumbInfo = ThumbInfo.Create(sm); //获取动画信息
        


              //格式化文件名去除特殊字符
                string reg = @"\:" + @"|\;" + @"|\/" + @"|\\" + @"|\|" + @"|\," + @"|\*" + @"|\?" + @"|\""" + @"|\<" + @"|\>";//特殊字符
                Regex r = new Regex(reg);
                title = r.Replace(thumbInfo.title, "");//将特殊字符替换为""

                movieType = thumbInfo.movieType;
                higt_Size = thumbInfo.sizeHigh;
                smType = "未知";
                Description = thumbInfo.Description; //详细
                ThumbnailUrl=thumbInfo.ThumbnailUrl; //预览图
                
               
               // StartDownload();
             
         
           
        }

      /// <summary>
      /// 获得flvinfo
      /// </summary>
      /// <param name="sm"></param>
      /// <returns></returns>
        private FlvInfo getflvinfo(string sm)
        {
            
            return  FlvInfo.Create(sm);
            
        }

        void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            this.IsDownloading = false;
            this.Speed = 0;
            if (!e.Cancelled)
            {
                this.IsCompleted = true;
            }
        }

        void client_DownloadProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e)
        {
            this.TotalBytes = e.TotalBytesToReceive;
            this.DownloadBytes = e.BytesReceived;
        }
        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }


        /// <summary>
        /// 计算速度
        /// </summary>
        /// <param name="milliseconds"></param>
        public void InitSpeed(int milliseconds)
        {
            if (IsCompleted) return;
            if (!IsDownloading) return;
            if (milliseconds <= 0) return;
            lock (syncObject)
            {
                var haveDownloaded = this.DownloadBytes - downloadedBytes;
                this.Speed = (haveDownloaded * 1000.0) / milliseconds;
               this.Progress= DownloadBytes * 100.0 / TotalBytes;
                downloadedBytes = this.DownloadBytes;
                this.xiazSize = tool.speedConvert(DownloadBytes) + "/" + tool.speedConvert(TotalBytes);
            }
        }
      /// <summary>
        /// 开始下载
        /// </summary>
        public void StartDownload()
        {
            try
            {
                path = AppDomain.CurrentDomain.BaseDirectory + "down";
                systool.Directory_jiany(path);
            if (client == null)
            {
                client = nicovideo.GetWebClientForFlv(smName);
            }
            IsDownloading = true; //设置下载标记
            xiazflag = 1;
            for (int i = 0; i < 10; i++)
            {
                if (!string.IsNullOrEmpty(smDownlUrl))
                {
                    break;
                }
                dl_getInfo dl = new dl_getInfo(getflvinfo);
                IAsyncResult ar = dl.BeginInvoke(smName, null, dl);
                sminfo = dl.EndInvoke(ar);
                smDownlUrl = sminfo.FlvUrl;
            }
            if (string.IsNullOrEmpty(smDownlUrl))
            {
                IsDownloading = false;
                xiazflag = -1;
                this.Speed = 0;
                return;
            }

            HttpWebRequest req = (HttpWebRequest)FileWebRequest.Create(smDownlUrl); //获取下载地址
            if (nico_data.proxy != null)
            {

                req.Proxy = nico_data.proxy;
            }
            req.CookieContainer = nicovideo.LoginCookie; //获取cookie
            //断点续传
            //if (DownloadBytes > 0)  //如果有下载数据
            //{
            //    req.AddRange(DownloadBytes); //设置开头
            //}

            
                //开始下载
                req.BeginGetResponse(ar =>
                {
                    try
                    {

                   
                     
                        var response = req.EndGetResponse(ar); //获取数据
                        if (this.TotalBytes == 0) this.TotalBytes = response.ContentLength;



                        if (this.TotalBytes < higt_Size)
                        {
                            smType = "低画质";

                        }
                        else
                        {
                            smType = "高画质";
                        }
                        
                        this.FileName = path + "\\" + title + "_" + smName + "_" + smType + "." + movieType;
                    

                     
                                           
                   
                    
                    using (var writer = new FileStream(this.FileName, FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.ReadWrite))
                    {
                        using (var stream = response.GetResponseStream()) //获得返回数据流
                        {
                            while (IsDownloading) //如果是下载状态
                            {
                                byte[] data = new byte[readBytes]; //设定接受2进制数据的大小
                                int readNumber = stream.Read(data, 0, data.Length); //读取固定数据
                                //如果读取到数据
                                if (readNumber > 0)
                                {
                                    writer.Write(data, 0, readNumber); //写入数据
                                    this.DownloadBytes += readNumber; //更新当前下载
                                }
                                //如果当前下载等于要下载字节数
                                if (this.DownloadBytes == this.TotalBytes)
                                {
                                    Complete(); //调用完成方法

                                }
                            }
                        }
                    }
                    }
                    catch (Exception ex)
                    {
                        if (ex.Message.ToString() == "不支持给定路径的格式。")
                        {
                            this.FileName = path + "\\" + title + "_" + smName + "_" + smType + "." + movieType;
                        }
                        else
                        {
                      //      tool.wf_log(ex.Message.ToString());
                            IsDownloading = false;
                            xiazflag = -1;
                            this.Speed = 0;

                        }
                    }

                }, null);
            }
            catch (Exception ex)
            {
                tool.wf_log(ex.Message.ToString());
                IsDownloading = false;
                xiazflag = -1;
                this.Speed = 0;
               
            }
           
        }
        public void Complete()
        {
            xiazflag = 2;
            this.IsDownloading = false;
             this.Progress = 100;
             this.xiazSize = tool.speedConvert(TotalBytes);
            this.Speed = 0;

        }

        public void PauseDownload()
        {
            xiazflag = 0;
            IsDownloading = false;
            this.Speed = 0;
        }
        public void DeleteFile()
        {

        }
        public event PropertyChangedEventHandler PropertyChanged;
    }
}
